import provinces from 'china-division/dist/provinces.json';
import cities from 'china-division/dist/cities.json';
import areas from 'china-division/dist/areas.json';

areas.forEach((area) => {
  const matchCity: any = cities.filter(
    (city) => city.code === area.cityCode,
  )[0];
  if (matchCity) {
    matchCity.children = matchCity.children || [];
    matchCity.children.push({
      label: area.name,
      value: area.code,
    });
  }
});

cities.forEach((city) => {
  const matchProvince: any = provinces.filter(
    (province) => province.code === city.provinceCode,
  )[0];
  if (matchProvince) {
    matchProvince.children = matchProvince.children || [];
    matchProvince.children.push({
      label: city.name,
      value: city.code,
      children: city.children,
    });
  }
});

interface OptionsInter {
  label: string;
  code: number;
  children: OptionsInter[];
}
const provinceOptions = provinces.map((province) => ({
  label: province.name,
  value: province.code,
  children: province.children,
}));

interface Location {
  code: string;
  name: string;
}

export function codeToName(areaCode: string): string[] {
  const location: Location[] = [];
  const area = areas.find((item) => item.code === areaCode);
  if (area) {
    location.push(area);
    const city = cities.find((item) => item.code === area?.cityCode);
    if (city) {
      location.push(city);
      const province = provinces.find((item) => item.code === city?.provinceCode);
      if (province) {
        location.push(province);
        if (['110000', '120000', '310000'].includes(province.code)) {
          return [province.name];
        }
      }
    }
  }
  return (location.map((item) => item.name).reverse());
}

export default provinceOptions;